// function double(num) {
//   return num * 2;
// }
// function square(num) {
//   return num * num;
// }

// var result = square(double(2));
// console.log(result);

// //简单组合函数
// function composeFn(fn1, fn2) {
//   return function (num) {
//     return fn2(fn1(num));
//   };
// }
// var newFn = composeFn(double, square);
// console.log(newFn(2));

// //通用组合函数
// function zhCompose(...fns) {
//   var length = fns.length;
//   for (let i = 0; i < length; i++) {
//     if (typeof fns[i] !== "function") {
//       throw new TypeError("arguments must be a function");
//     }
//   }
//   return function (...argus) {
//     var index = 0;
//     var result = length ? fns[index].apply(this, argus) : argus;
//     while (++index < length) {
//       result = fns[index].call(this, result);
//     }
//     return result;
//   };
// }
// var newFn2 = zhCompose(double, square);
// console.log(`newFn2(2);`, newFn2(2));

//获取剩余参数长度， 判断参数重是否有不是函数的
// 返回一个函数， 函数中循环调用每一个函数

// 组合式函数的实现

function fn1(num) {
  return num * 2;
}
function fn2(num) {
  return num + 4;
}

// console.log(`fn2(fn1(2))`, fn2(fn1(9)));

function compose(...fns) {
  for (let i = 0; i < fns.length; i++) {
    if (typeof fns[i] !== "function") {
      throw new TypeError("expect arguments are function");
    }
  }
  return function (...args) {
    let index = 0;
    let result = fns[index].apply(this, args);
    while (++index < fns.length) {
      result = fns[index].call(this, result);
    }
    return result;
  };
}
var newFn = compose(fn1, fn2);
console.log(newFn(2));
